
#include <BFile>
#include <BFileInfo>

#include "Bitmap.h"
#include "ReadWrite_bmp.h"

ReadWrite_bmp::ReadWrite_bmp()
{
	_author = "zym";
	_version = "1.0";
	_description = "This is BWE Plugin for reading *.bmp image file, write width libjpeg, thank a lot !";
}
ReadWrite_bmp::~ReadWrite_bmp()
{

}

const BString& ReadWrite_bmp::author() const
{
	return _author;
}
const BString& ReadWrite_bmp::version() const
{
	return _version;
}
const BString& ReadWrite_bmp::description() const
{
	return _description;
}
const BString& ReadWrite_bmp::log() const
{
	return _log;
}

/***************************************
	BM	Windows 3.1x, 95, NT
	BA	OS/2 Bitmap Array
	CI	OS/2 Color Icon
	CP	OS/2 Color Pointer
	IC	OS/2 Icon
	PT	OS/2 Pointer
*/
char	dentifier[2];
unsigned int	fileSize;
unsigned int	reserved;
unsigned int	dataOffset;
unsigned int	headerSize;

unsigned int	width;
unsigned int	height;
unsigned short	planes;
unsigned short	pixelBits;

unsigned int	compression;
unsigned int	dataSize;
unsigned int	HResolution;
unsigned int	VResolution;

unsigned int	colors;
unsigned int	importantColors;
/********************************/

void initHeader()
{
	dentifier[0] = 0;
	dentifier[1] = 0;
	fileSize = 0;
	reserved = 0;
	dataOffset = 0;
	headerSize = 0;
	
	width = 0;
	height = 0;
	planes = 0;
	pixelBits = 0;
	
	compression = 0;
	dataSize = 0;
	HResolution = 0;
	VResolution = 0;
	
	colors = 0;
	importantColors = 0;
}

bool ReadWrite_bmp::readObject(const BString& fileName, BObject* object)
{
	BImage* image = dynamic_cast<BImage*>(object);
	if (!image)
		return false;

	BFile file(fileName);
	if (!file.open(BFile::Mode_Read))
		return false;

	initHeader();

	file.read(dentifier, 2);
	file.read(fileSize);
	file.read(reserved);
	file.read(dataOffset);

	file.read(headerSize);
	file.read(width);
	file.read(height);
	file.read(planes);

	file.read(pixelBits);
	file.read(compression);
	file.read(dataSize);

	file.read(HResolution);
	file.read(VResolution);
	file.read(colors);
	file.read(importantColors);

	Format format = Format_None;
	if (pixelBits == 8)
		format = Format_Gray;
	if (pixelBits == 24)
		format = Format_RGB;

	if (format)
	{
		int pixelSize = width * height * pixelBits / 8;
		BByteArray* pixels = new BByteArray(pixelSize);
		file.seek(dataOffset);
		file.read(pixels->data(), pixelSize);

		if (format == Format_RGB)
		{
			BByte* bytes = pixels->data();
			for (int i = 0; i < pixelSize; i += 3)
			{
				BByte temp = bytes[i];
				bytes[i] = bytes[i + 2];
				bytes[i + 2] = temp;
			}
		}

		image->setFormat(format);
		image->setWidth(width);
		image->setHeight(height);
		image->setPixels(pixels);
	}

	file.close();

	return true;
}
bool ReadWrite_bmp::writeObject(const BString& fileName, const BObject* object)
{
	return false;
}

